<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option
          :label="item.tmName"
          v-for="(item, index) in AllTradeMark"
          :key="item.id"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请输入描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无'
        "
        v-model="saleAttrIdAndValueName"
      >
        <el-option
          :label="item.name"
          v-for="(item, index) in unSelectSaleAttr"
          :key="item.id"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        icon="Plus"
        style="margin-left: 10px"
        :disabled="!saleAttrIdAndValueName"
        @click="onAddSaleAttr"
      >
        添加属性
      </el-button>
    </el-form-item>
    <el-form-item label="">
      <el-table style="margin: 20px 0" border stripe :data="saleAttrList">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="100px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          align="center"
          width="150px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值" align="center">
          <template #="{ row, $index }">
            <el-tag
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              closable
              style="margin: 0 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag"
              placeholder="请输入属性值"
              size="small"
              v-model="row.saleAttrValue"
              @blur="toLook(row)"
              style="width: 100px"
            />
            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="toEdit(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="saleAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="onSave"
        :disabled="saleAttrList.length <= 0"
      >
        保存
      </el-button>
      <el-button type="primary" @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import {
  AllTradeMark,
  HasSaleAttr,
  HasSaleAttrResponseData,
  SaleAttr,
  SaleAttrResponseData,
  SaleAttrValue,
  SpuData,
  SpuHasImg,
  SpuImg,
} from '@/api/product/spu/type.ts'
import {
  reqAddOrUpdateSpu,
  reqAllSaleAttr,
  reqAllTradeMark,
  reqSpuHasSaleAttr,
  reqSpuImageList,
} from '@/api/product/spu'
import {TradeMark} from '@/api/product/trademark/type.ts'
import {computed, ref, UnwrapRef} from 'vue'
import {ElMessage} from 'element-plus'
import {CategoryState} from '@/store/modules/types/type.ts'

let $emit = defineEmits(['changeScene'])

// 点击取消
const onCancel = () => {
  $emit('changeScene', {flag: 0, params: 'update'})
}
// 存储已有的spu数据
let AllTradeMark = ref<TradeMark[]>([])
// 商品图片
let imgList = ref<SpuImg[]>([])
// 已有的spu销售属性
let saleAttrList = ref<SaleAttr[]>([])
// 所有的销售属性
let allSaleAttr = ref<HasSaleAttr>([])
// 存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: '', // 收集三级分类的ID
  spuName: '', // SPU的名字
  description: '', // SPU的描述
  tmId: '', // 品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
})
// 控制对话框显示隐藏
let dialogVisible = ref<boolean>(false)
// 存储预览图片地址
let dialogImageUrl = ref<string>('')
// 将来收集还未选择的销售属性ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')
const initHasSpuData = async (spu: SpuData) => {
  // 存储已有的SPU对象
  SpuParams.value = spu
  // 获取全部品牌的数据
  let result: AllTradeMark[] = await reqAllTradeMark()
  // 获取某一个品牌旗下全部售卖商品的图片
  let result1: SpuHasImg = await reqSpuImageList(spu.id)
  // 获取已有spu销售属性
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id)
  // 获取所有的spu销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()
  // 存储全部品牌的数据
  AllTradeMark.value = result.data
  // 存储spu对应商品的图片
  imgList.value = result1.data.map(
    (item: { imgName: string; imgUrl: string }) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    },
  )
  // 存储已有spu销售属性
  saleAttrList.value = result2.data
  // 存储所有的销售属性
  allSaleAttr.value = result3.data
}
// 照片墙点击预览按钮
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
// 删除照片墙
const handleRemove = () => {
}
// 照片墙上传成功之前的约束
const handlerUpload = (file: any) => {
  if (
    file.type === 'image/png' ||
    file.type === 'image/jpeg' ||
    file.type === 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '图片体积不得大于3MB',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件类型必须是PNG、JPG、GIF之一',
    })
    return false
  }
}
// 计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  return allSaleAttr.value.filter((item: { name: string }) => {
    return saleAttrList.value.every((item1: { saleAttrName: string }) => {
      return item.name != item1.saleAttrName
    })
  })
})
// 点击添加属性
const onAddSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  saleAttrList.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}
// 属性值的点击事件
const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}
// 表单原生失去焦点
const toLook = (row: SaleAttr) => {
  // 收集到的属性的ID与属性值的名字
  const {baseSaleAttrId, saleAttrValue} = row
  // 整理成服务器需要的格式
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue,
  }
  // 非法情况判断
  if (saleAttrValue.trim() === '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
  }
  // 判断属性值是否在数组中存在
  let repeat = row.spuSaleAttrValueList.find(
    (item: { saleAttrValueName: string }) => {
      return item.saleAttrValueName === saleAttrValue
    },
  )
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复',
    })
    return
  }
  // 追加新的属性值
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  // 切换为查看模式
  row.flag = false
}
// 点击保存
const onSave = async () => {
  // 整理参数
  // 照片墙数据
  SpuParams.value.spuImageList = imgList.value.map(
    (item: { name: string; response: { data: string }; url: string }) => {
      return {
        imgName: item.name,
        imgUrl: (item.response && item.response.data) || item.url,
      }
    },
  )
  // 整理销售属性的数据
  SpuParams.value.spuSaleAttrList = saleAttrList.value
  console.log(SpuParams.value)
  let result = await reqAddOrUpdateSpu(SpuParams.value)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    $emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
// 添加一个新的SPU
const initAddSpu = async (c3Id: number | string) => {
  // 清空数据
  Object.assign(SpuParams.value, {
    category3Id: '', // 收集三级分类的ID
    spuName: '', // SPU的名字
    description: '', // SPU的描述
    tmId: '', // 品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  // 清空照片
  imgList.value = []
  // 清空销售属性
  saleAttrList.value = []
  saleAttrIdAndValueName.value = ''
  // 存储三级分类的ID
  SpuParams.value.category3Id = c3Id
  // 获取全部品牌的数据
  let result: AllTradeMark = await reqAllTradeMark()
  // 获取所有的spu销售属性
  let result1: HasSaleAttrResponseData = await reqAllSaleAttr()
  // 存储数据
  AllTradeMark.value = result.data
  allSaleAttr.value = result1.data
}
defineExpose({initHasSpuData, initAddSpu})
</script>
<style scoped lang="scss"></style>
